/*
 * TCSS 422 - Spring quarter 2011
 * Team: 	Googlers
 * Members: Deepa Sahni, Krisnil Gounder, Michael Schweiger
 * Date: 	April 25, 2011
 */
package buffers;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * A buffer designed to hold URL objects.  This buffer will only hold a unique URL once
 * within its lifetime (keeps track of URLs seen).  This object is a Singleton.
 * Null elements are not allowed in this buffer.
 * @author Michael Schweiger
 * @version 1.0
 */
public final class URLBuffer extends Buffer<URL> {

	/**
	 * The singleton instance of this PageBuffer.
	 */
	private static final URLBuffer my_instance = new URLBuffer();
	
	/**
	 * The set of seen URLs.
	 */
	private final Set<String> my_seen_urls;
		
	/**
	 * Returns a singleton instance of this PageBuffer.
	 * @return The PageBuffer
	 */
	public static URLBuffer getInstance() {
		return my_instance;
	}

	/**
	 * Used privately for instantiation and to prevent outside instantiation.
	 */
	private URLBuffer() {
		super(false);
		my_seen_urls = new HashSet<String>();
	}
	
	/**
	 * Attempt to add a URL.  Returns true if successfully added.  Will only accept urls
	 * that end in .txt, .htm, or .html
	 * Per requirements, any URL that starts with http://questioneverything.typepad.com/
	 * will not be added.
	 * @throws IllegalArgumentException if url is null.
	 * @param url The URL to add.
	 * @return true if successfully added (not seen before), false otherwise.
	 */
	public synchronized boolean add(URL url) throws IllegalArgumentException {
		String url_address = url.toString().toLowerCase();
		String url_file = url.getFile();
		if (!url_address.startsWith("http://")) {
			return false;
		}
		if (url_file.isEmpty() || url_address.endsWith("/")) {
			URL newURL = null;
			try {
				String new_address = url_address;
				if (url_file.isEmpty()) {
					new_address = new_address + "/";
				}
				newURL = new URL(new_address + "index.html");
				return add(newURL);
			} catch (MalformedURLException e) {
				//e.printStackTrace();
			}
			return false; //if the url didn't form right.
		}
		if (url_address.startsWith("http://questioneverything.typepad.com/")) {
			return false;
		} else if (!(url_address.endsWith(".txt") || url_address.endsWith(".html") 
				|| url_address.endsWith(".htm"))) {
			return false;
		} else if (my_seen_urls.contains(url.toString())) {
			return false;
		} else {
			my_seen_urls.add(url.toString());
			return super.add(url);
		}
	}
	
	/**
	 * Returns the number of elements that have been seen by this buffer.
	 * @return the number of elements that have been seen by this buffer.
	 */
	public synchronized int getSeenCount() {
		return my_seen_urls.size();
	}
}
